<?php

namespace app\utils\Service\AliCloud;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use app\utils\Service\Library;
use AlibabaCloud\Tea\Exception\TeaError;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class AliSms extends Library
{
    private $AccessKeyId;//id
    private $AccessSecret;//key
    private $SignName;//短信签名

    /**
     * 实例化
     */
    public function __construct()
    {
        // 获取配置信息
        $this->AccessKeyId  = (string)config('site.ali_access_key_id');
        $this->AccessSecret = (string)config('site.ali_access_secret');
        $this->SignName     = (string)config('site.ali_sign_name');
    }

    /**
     * 使用AK&SK初始化账号Client
     * @return Dysmsapi Client
     */
    public function createClient(){
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html。
        $config = new Config([
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
            "accessKeyId" => $this->AccessKeyId,
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
            "accessKeySecret" => $this->AccessSecret
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * 发送短信
     * @param string $mobile
     * @param array $authData
     * @return bool
     */
    public function send(string $mobile, array $authData): bool
    {
        $client = $this->createClient();
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $mobile,
            "signName" => $this->SignName,
            "templateCode" => "SMS_469005749",
            "templateParam" => json_encode($authData, JSON_UNESCAPED_UNICODE)
        ]);

        try {
            // 复制代码运行请自行打印 API 的返回值
            $res = $client->sendSmsWithOptions($sendSmsRequest, new RuntimeOptions([]));
        } catch (\Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 错误 message $error->message
            // 诊断地址 $error->data["Recommend"]
            return $this->error($error->message,$error->data);
        }
        if ($res->body->code != 'OK'){
            return $this->error($res->body->message);
        }

        return $this->success('发送成功');
    }
}